package cn.analysis.framework.web.exception;

import cn.analysis.common.ResultCode;
import cn.analysis.common.ResultVO;
import cn.analysis.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import cn.analysis.common.exception.*;

/** 全局异常处理 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /** 基础异常 */
    @ExceptionHandler(BaseException.class)
    public ResultVO baseException(BaseException e) {
        return ResultVO.error(e.getMessage());
    }

    /** 业务异常 */
    @ExceptionHandler(CustomException.class)
    public ResultVO businessException(CustomException e) {
        if (StringUtils.isNull(e.getCode())) {
            return ResultVO.error(e.getMessage());
        }
        return ResultVO.error(e.getCode(), e.getMessage());
    }

    /** not found 异常 */
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultVO handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return ResultVO.error(ResultCode.NOT_FOUND);
    }
}
